<template>
  <el-dialog
      v-model="dialogVisible"
      title="分配骑手"
      width="50%"
      @close="handleClose"
  >
    <el-table
        v-loading="loading"
        :data="filteredRiderList"
        @selection-change="handleSelectionChange"
        highlight-current-row
        stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="骑手ID" align="center" prop="riderId" width="100" />
      <el-table-column label="姓名" align="center" prop="name" width="120" />
      <el-table-column label="手机号" align="center" prop="phone" width="150" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '可用' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" width="120">
        <template #default="{row}">
          <el-tag :type="row.auditStatus === 1 ? 'success' : 'warning'">
            {{ row.auditStatus === 1 ? '已审核' : '未审核' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, reactive, toRefs, computed } from 'vue'
import { listRider } from "@/api/system/rider"
import { ElMessage } from 'element-plus'
import {updateAssignOrders} from "@/api/system/assignOrders.js";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  orderId: {
    type: [String, Number],
    default: ''
  }
})

const emit = defineEmits(['update:visible', 'assign'])

const dialogVisible = ref(props.visible)
const loading = ref(false)
const selectedRider = ref(null)

const state = reactive({
  riderList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    phone: null,
    status: 1,
    auditStatus: 1  // 可以添加审核状态作为查询参数
  },
  total: 0
})

const { riderList, queryParams, total } = toRefs(state)

// 计算属性，过滤出状态为1且审核状态为1的骑手
const filteredRiderList = computed(() => {
  return riderList.value.filter(rider => rider.status === 1 && rider.auditStatus === 1)
})

/** 查询骑手列表 */
function getList() {
  loading.value = true,
      listRider(queryParams.value).then(response => {
        riderList.value = response.rows
        total.value = response.total
        loading.value = false
      }).catch(() => {
        loading.value = false
      })
}

// 选中骑手数据
function handleSelectionChange(selection) {
  selectedRider.value = selection.length > 0 ? selection[0] : null
}

watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    getList()
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

const handleClose = () => {
  selectedRider.value = null
}

const handleSubmit = async () => {
  if (!selectedRider.value) {
    ElMessage.warning('请选择要分配的骑手')
    return
  }

  try {
    // 调用后端API，传递订单ID、骑手ID和status
    await updateAssignOrders({
      id: props.orderId, // 添加订单ID
      riderId: selectedRider.value.riderId,
      status: 1
    })

    // 提交成功后关闭弹窗
    dialogVisible.value = false
    ElMessage.success('分配成功')

    // 通知父组件分配成功
    emit('assign', {
      orderId: props.orderId,
      riderInfo: selectedRider.value // 传递完整的骑手信息
    })
  } catch (error) {
    ElMessage.error('分配失败：' + (error.message || error))
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>